import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/conversation/messagesPage.dart';
import 'package:bai_le_men_im/pages/sendFriendRequest.dart';
import 'package:bai_le_men_im/pages/setFriendAlias.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../models/index.dart';
import 'package:async/async.dart';
import '../constants.dart' show Constants;

class UserDetailPage extends StatefulWidget {
  final User userData;
  final bool isMyFriend;

  UserDetailPage({this.userData, this.isMyFriend = false});
  @override
  _UserDetailPageState createState() => _UserDetailPageState();
}

class _UserDetailPageState extends State<UserDetailPage> {
  deleteFriend() async {
    try {
      await FlutterWildfire.deleteFriend(widget.userData.uid);
      print('deleteFriend ok');
    } catch (e) {
      print('deleteFriend error');
      print(e);
    } finally {
      Navigator.pop(context, {
        "type": "deleteFriend",
        "payload": {"userId": widget.userData.uid}
      });
    }
  }

  bool isMyFriend;
  final AsyncMemoizer _memoizer = AsyncMemoizer();

  targetIsMyFriend() {
    return _memoizer.runOnce(() async {
      String userId = widget.userData.uid;
      bool isMyFriend = await FlutterWildfire.isMyFriend(userId);

      return {"isMyFriend": isMyFriend, "user": widget.userData};
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: targetIsMyFriend(),
        builder: (BuildContext context, AsyncSnapshot snapShop) {
          if (!snapShop.hasData) {
            return CircularProgressIndicator();
          }
          final User userData = widget.userData;
          bool isMyFriend = snapShop.data["isMyFriend"] ?? false;
          final String name =
              userData.friendAlias != null && userData.friendAlias.isNotEmpty
                  ? userData.friendAlias
                  : userData.displayName;
          return Scaffold(
              backgroundColor: Colors.grey[350],
              appBar: AppBar(
                iconTheme: Theme.of(context).iconTheme,
                elevation: 0.0,
                backgroundColor: Colors.white,
                // title: Text('用户信息'),
                actions: <Widget>[
                  widget.isMyFriend
                      ? FlatButton(
                          onPressed: deleteFriend,
                          child: Text('删除'),
                        )
                      : Container()
                ],
              ),
              body: ListView(
                children: <Widget>[
                  Container(
                    color: Colors.white,
                    child: Column(
                      children: <Widget>[
                        Container(
                          color: Colors.white,
                          child: Padding(
                            padding: const EdgeInsets.all(18.0),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                ClipRRect(
                                    borderRadius: BorderRadius.circular(
                                        Constants.AvatarRadius),
                                    child: myAvatar(userData.portrait,
                                        size: 90.0)),
                                SizedBox(
                                  width: 10.0,
                                ),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          name,
                                          style: TextStyle(fontSize: 22.0),
                                        ),
                                        SizedBox(
                                          width: 5.0,
                                        ),
                                        myGenderIcon(userData.gender, 40.0)
                                      ],
                                    ),
                                    userData.name != null &&
                                            userData.name.isNotEmpty
                                        ? Text('账号：${userData.name}')
                                        : Container(),
                                    userData.displayName != null &&
                                            userData.displayName.isNotEmpty
                                        ? Text('昵称：${userData.displayName}')
                                        : Container(),
                                    userData.address != null &&
                                            userData.address.isNotEmpty
                                        ? Text('地址：${userData.address}')
                                        : Container()
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                        Divider(
                          height: 0.0,
                        ),
                        isMyFriend
                            ? (ListTile(
                                onTap: () {
                                  Navigator.of(context).push(
                                      new MaterialPageRoute(builder: (context) {
                                    return SetFriendAliasPage(
                                      user: widget.userData,
                                    );
                                  }));
                                },
                                title: Text('设置备注和标签'),
                                trailing: Icon(Icons.chevron_right),
                              ))
                            : (Container())
                      ],
                    ),
                  ),
                  Divider(
                    height: 0.0,
                  ),
                  SizedBox(
                    height: 10.0,
                  ),
                  isMyFriend
                      ? MaterialButton(
                          elevation: 0.0,
                          padding: EdgeInsets.symmetric(vertical: 10.0),
                          color: Colors.white,
                          textColor: Colors.blueAccent,
                          onPressed: () async {
                            var result = await Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return MessagesPage(user: widget.userData);
                            }));
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Icon(Icons.chat,
                                  size: 18.0, color: Colors.blueGrey[700]),
                              SizedBox(
                                width: 10.0,
                              ),
                              Text(
                                '发消息',
                                style: TextStyle(
                                    fontSize: 17.0,
                                    color: Colors.blueGrey[700]),
                              )
                            ],
                          ),
                        )
                      : MaterialButton(
                          elevation: 0.0,
                          padding: EdgeInsets.symmetric(vertical: 10.0),
                          color: Colors.white,
                          textColor: Colors.blueAccent,
                          onPressed: () async {
                            var result = await Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return SendFriendRequest(
                                  userData: widget.userData);
                            }));
                          },
                          child: Text(
                            '添加到通讯录',
                            style: TextStyle(fontSize: 17.0),
                          ),
                        )
                ],
              ));
        });
  }
}
